package csc.fresher.commons;

import java.sql.Date;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;


@FacesValidator("durationValidator")
public class DurationValidator implements Validator {

	@Override
	public void validate(FacesContext context, UIComponent component,
			Object value) throws ValidatorException {
		String fromDate = value.toString();
		
		UIInput uiInputToDate = (UIInput) component.getAttributes().get("toDate");
		String toDate = uiInputToDate.getSubmittedValue().toString();
		
		SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
		try {
			Date frommDateFormat = new java.sql.Date(format.parse(fromDate).getTime());

			Date toDateFormat = new java.sql.Date(format.parse(toDate).getTime());
		
			if (frommDateFormat.after(toDateFormat)) {
				throw new ValidatorException(new FacesMessage("Invalid duration."));
			} else if ((toDateFormat.getTime()-frommDateFormat.getTime())>(90*24*60*60*1000L)) {
				System.out.println(toDateFormat.getTime()-frommDateFormat.getTime());
				throw new ValidatorException(new FacesMessage("Your duration must less than 90 days"));
			} 
			
		} catch (ParseException e) {
			throw new ValidatorException(new FacesMessage("Invalid Date Format. Please use datepicker to select date."));
		}
		return;
	}

}
